import 'dart:async';

import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qunaimedical/components/item_moment.dart';
import 'package:qunaimedical/models/category.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/moment.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/event_bus_manager.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/constants.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:sprintf/sprintf.dart';

class MomentList extends StatefulWidget {
  final Category category;

  const MomentList({Key key, this.category}) : super(key: key);

  @override
  _MomentListState createState() => _MomentListState();
}

class _MomentListState extends State<MomentList> {
  List<Moment> _items = [];

  RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  // 是否有下一页
  int _nextPage = 1;

  StreamSubscription notifier;

  @override
  void initState() {
    super.initState();
    notifier = eventBus.on<EventBusManager>().listen((event) {
      if (event.eventKey == EventBusManager.momentRefresh) {
        _fetchData();
      }
    });
  }

  @override
  void dispose() {
    notifier.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      enablePullUp: _nextPage != 1,
      onRefresh: _fetchData,
      onLoading: _loadMore,
      child: ListView.builder(
        padding: EdgeInsets.only(bottom: 50),
        itemBuilder: (c, i) => ItemMoment(
          _items[i],
          clickAble: true,
        ),
        itemCount: _items.length,
      ),
    );
  }

  void _fetchData() async {
    var result = await XHttp.postJson(
        sprintf(Urls.moment_list, [1, Constants.limit]),
        {'postInfoType': widget.category.value});
    _refreshController.refreshCompleted();
    if (result != null) {
      var response = MapResponse.fromJson(result);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => Moment.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items = records;
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _loadMore({Map<String, dynamic> condition}) async {
    var result = await XHttp.postJson(
        sprintf(Urls.moment_list, [_nextPage, Constants.limit]),
        {'postInfoType': widget.category.value});
    _refreshController.loadComplete();
    if (result != null) {
      var response = MapResponse.fromJson(result);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => Moment.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items.addAll(records);
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }
}
